package com.boot.study.jianfan;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author lkz
 * @className PdfGeneratorAndUploader
 * @description 生成pdf打成压缩包上传文件服务器
 * @date 2024/3/7 11:15
 **/
public class PdfGeneratorAndUploader {


    private final String pageId="pageId";



    public static void main(String[] args) throws IOException {
        // 设置阿里云OSS配置
        String endpoint = "oss-cn-shanghai.aliyuncs.com";
        String accessKeyId = "LTAI5tGCjJiRgHxCQLiCWqUR";
        String accessKeySecret = "Hz69as0UxRnqM4Svks4Ewec19UR4Wt";
        String bucketName = "jianfan2";

//        LTAI5tJaBGVACj3R7Z6Guy6T
//        3EobD9FkXqv1QYe3amU1xYdTqGVUAm

        // 创建临时文件夹
        Path tempDir = Files.createTempDirectory("generated_pdfs_");

        // 假设generatePdf方法接收文件名作为参数，并在指定路径下生成PDF文件
        List<Path> pdfFiles = new ArrayList<>();
        FormPdfDemo2 pdfDemo2= new FormPdfDemo2();
        for (int i = 0; i < 10; i++) {
            String pdfName = "generated_pdf_" + i + ".pdf";
            Path pdfPath = tempDir.resolve(pdfName);
            String path = pdfPath.toFile().getPath();
           // pdfDemo2.createDocument2(path);
            pdfFiles.add(pdfPath);

        }

        // 压缩临时文件夹
        Path zipFile = Paths.get("output.zip");
        compressDirectory(tempDir, zipFile);

        // 初始化OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传ZIP文件到阿里云OSS
        uploadToOSS(ossClient, bucketName, zipFile);

        // 关闭OSS客户端
        ossClient.shutdown();

        // 清理临时文件夹
        Files.walk(tempDir)
                .sorted(Comparator.reverseOrder())
                .map(Path::toFile)
                .forEach(File::delete);
    }


    // 压缩目录
    private static void compressDirectory(Path dir, Path zipfile) throws IOException {
        try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(zipfile.toFile()))) {
            Files.walk(dir)
                    .filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        ZipArchiveEntry zipEntry = new ZipArchiveEntry(dir.relativize(path).toString());
                        try (InputStream is = Files.newInputStream(path)) {
                            zos.putArchiveEntry(zipEntry);
                            IOUtils.copy(is, zos);
                            zos.closeArchiveEntry();
                        } catch (IOException e) {
                            System.err.println("Error adding file to ZIP: " + path);
                        }
                    });
        }
    }

    // 将ZIP文件上传至阿里云OSS
    private static void uploadToOSS(OSS ossClient, String bucketName, Path localFile) {
        String objectName = "output.zip"; // OSS上的目标文件名
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, localFile.toFile());
        try {
            ossClient.putObject(putObjectRequest);
            System.out.println("ZIP file uploaded to OSS successfully.");
        } catch (OSSException  e) {
            System.err.println("Error occurred when uploading ZIP file to OSS: " + e.getMessage());
        }
    }


}
